package com.wshoto.delayed;

import org.redisson.Redisson;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;

import java.util.concurrent.TimeUnit;

public class DelayedProducer {
    public static void main(String[] args) {
        String redisAddress = "redis://120.24.195.35:6379";
        String redisPassword = "Wang103750";
        String queueName = "delayedQueue";
        long secondDelay = 50;
        Config config = new Config();
        config.setCodec(new JsonJacksonCodec());
        config.useSingleServer().setAddress(redisAddress).setPassword(redisPassword)
                .setDatabase(0);
        RedissonClient redissonClient = Redisson.create(config);
        RBlockingQueue<MessageInfo> blockingFairQueue = redissonClient.getBlockingQueue(queueName);
        RDelayedQueue<MessageInfo> delayedQueue = redissonClient.getDelayedQueue(blockingFairQueue);
        for(int i = 0; i < 100; i++) {
            String message = "我是定时消息，" + secondDelay + "秒后被消费";
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setId(i);
            messageInfo.setContent(message + i);
            delayedQueue.offer(messageInfo, secondDelay, TimeUnit.SECONDS);
            MessageInfo peek = delayedQueue.peek();
            System.out.println(peek);
        }
        //注意生产端发送消息后需要保持和redis的连接，否则延迟消息不生效
    }
}
